#include <libglademm/xml.h>
#include <gtkmm.h>
#include <iostream>	//for cout only
using namespace std;
using Glib::ustring;
#include "pic.h"
#include <fstream>
#include <string>
#include <sstream>

Gtk::Statusbar*		pS=0;
Gtk::Window*		pW=0;
Gtk::Calendar*		pC=0;
Gtk::Image*		pI1=0;
Gtk::Image*		pI2=0;
Gtk::Image*		pI3=0;
Gtk::Image*		pI4=0;
Gtk::Image*		pI5=0;
Gtk::Image*		pI6=0;
Gtk::Image*		pI7=0;
Gtk::Image*		pI8=0;
Gtk::Label*		pL=0;
Gtk::ToggleButton*	T_calendar=0;
//Gtk::ToggleButton*	pT2=0;
Gtk::Button*		B_today=0;
Gtk::Button*		B_edit_in=0;
Gtk::Button*		B_edit_out=0;
Gtk::Button*		B_chart_year=0;
Gtk::Button*		B_chart_month=0;

#define	MaxSelect	9
ustring		input;	//保存输入，使用类似格式：xc2:6.5，输入接受a-z.0-9
ustring		item;	//保存类型，输入接受a-z1-9<backspace><esc>
ustring		value;	//保存数据，输入接受0-9.<backspace><enter><esc>
ustring		def_v;	//缺省数据。
ustring		result_str;	//显示的选择数据。
string		result[MaxSelect][3];	//匹配的，可选的前面9个类型。3个字段。
guint		can_sel_num;
//char	appdir[200];
const ustring	date[]={"天前","前天","昨天","今天","明天","后天","天后"};
#define DateType	7
#define	ItemFile	"items"
#define	RecordFile	"record"
#define	GladeFile	"ea.glade"

//#define	PlotData	"gnuplot.dat"
//#define	PlotDem		"gnuplot.dem"
//#define	PlotPic		"gnuplot.png"
//#define IconFile	"icon.png"
Glib::Date	sel_date,today,last_saved_date(10);
Glib::RefPtr<Gdk::Pixbuf>	pix;
//bool mask_key(GdkEventKey* ev)
//{
//   return true;
//}
//======================================================
//void create-data(bool month-or-year)
//{
//FILE *fin;
//char s[120];
//char *p;
//float total[32],sum=0;
//int day=0,i,len;
//        if(argv[1]==NULL) 
//        {printf("Version 0.2\nUsage:\tformat parameter of totalizing month: '2008-01'.\n\tformat parameter of totalizing year: '2008'\n");return 2;}

//        len=strlen(argv[1]);
//        for(i=0;i<32;i++) total[i]=0;
//        fin=fopen("record", "r");
//        if(fin==NULL) return 1;
//        while(fgets(s, 100, fin)!=NULL){
//                if(strchr(s,'=')){	//以====为行首的日期行
//                        if(strstr(s,argv[1])){
//                                p=strrchr(s,'-');	//月统计，行尾查找日期
//                                if(len<6){
//                                        *p=0;
//                                        p=strrchr(s,'-');	//年统计，行尾查找月份
//                                        }
//                                p++;
//                                day=atoi(p);
//                        } else day=0;
//                } else{		//数据行
//                        if(day==0) continue;
//                        p=strchr(s,',');
//                        p++;
//                        total[day]+=strtof(p,NULL);
//                }
//        }
//        for (i=1;i<(len>4?32:12);i++){
//                sum+=total[i];
//                if(total[i]) printf("[%02d] %.2f\t",i,total[i]);
//                if(i%5==0) printf("\n");
//                }
//        if(len>4)
//        printf("\n====== total of month: %.2f\n",sum);
//        else
//        printf("\n====== total of year: %.2f\n",sum);
//        fclose(fin);
//}
//======================================================
void date_display(int index)
{
	int i=index;
	i+=3; 
	if(i<0)i=0; if(i>DateType-1)i=DateType-1;
	//index%=DateType;	//需要自动取得date[]的上限。
	pI1->set(Gdk::Pixbuf::create_subpixbuf(pix, i*24, 0, 24, 24));
	//需要判断图标序列的高度。int 	get_height () const？？？
	if(i>0 && i<DateType-1)pS->push(date[i]);else{
		//丑陋的int转字符串
		char t[256];
		sprintf(t,"%d",index);
		pS->push(ustring(ustring(t)+date[i]));}
}
//======================================================
void display()
{
	if(input==""){pL->set_label("<b><big><span color='grey'>输入字母缩写</span></big></b>");return;}
	if(item==""){pL->set_label("<span color='blue'>"+result_str+"</span>\n<b><big><span color='red'>"+input+"</span></big></b><span color='grey'> 用数字选择类型</span>");return;}
	if(def_v!=""&&value==""){pL->set_label("<b><big><span color='red'>"+item+": </span></big></b><span color='green'>默认值 "+def_v+"</span>\n<span color='grey'>回车确定或输入数字修改。</span>");return;}
	pL->set_label("<b><big><span color='red'>"+item+": </span><span color='blue'>"+value+"</span></big></b>\n<span color='grey'>输入数据。回车确定。</span>");
}
//======================================================
void cancel()
{
	input="";item="";value="";def_v="";result_str="";
	display();
}
//======================================================
void save()
{
	std::ofstream fout(RecordFile,ios::app);
//cout<<today.format_string("%H:%M ")<<endl;
	if(last_saved_date!=sel_date){
		fout<<"========"<<sel_date.format_string("%Y-%m-%d")<<endl;
		last_saved_date=sel_date;
	} 
	fout << item << "," << value;
//        if(pT2->property_active()&&pT2->is_visible()){
//                struct tm *local;
//                time_t t;
//                time(&t);
//                local=localtime(&t);
//                fout<<","<<local->tm_hour<<":"<<local->tm_min;
//printf("Local hour is: %d %d\n",local->tm_hour,local->tm_min);
//char str[100];
//strftime(str,100,"%H:%M",local);
//cout<<ustring(str)<<endl;
//                }
	fout << endl;
	cancel();
	fout.close();
}
//======================================================
void on_calendar1_day_selected()
{
	int i;
	pC->get_date(sel_date);
	i=today.days_between(sel_date);
	date_display(i);
//        if(i==0)pT2->show();else pT2->hide();
}
//void next_day()
//{
//        int i;
//        pC->get_date(sel_date);
//        i=today.days_between(sel_date);
//        i++;
//        date_display(i);
//}
//void last_day()
//{
//        int i;
//        pC->get_date(sel_date);
//        i=today.days_between(sel_date);
//        i--;
//        date_display(i);
//}
//======================================================
void on_T_calendar_toggled()
{
	if(pC->is_visible()) pC->hide(); else pC->show();
}
//======================================================
void on_B_today_clicked()
{
	//设置日历为今天。丑陋的日历，没方法set。
	pC->select_month(today.get_month()-1, today.get_year());
	pC->select_day(today.get_day());
	date_display(0);
}
void on_edit_in_clicked()
{
	system("gvim items");
}
void on_edit_out_clicked()
{
	system("gvim record");
}
void on_chart_year_clicked()
{
char cmd[256];
//        sprintf(cmd,"cd %s; ./chart %d",appdir,sel_date.get_year());
	sprintf(cmd,"cd %s; ./chart.bash %d",g_get_current_dir(),sel_date.get_year());
	cout<<cmd<<endl;
	system(cmd);
}
void on_chart_month_clicked()
{
char cmd[256];
	sprintf(cmd,"cd %s; ./chart.bash %4d-%02d",g_get_current_dir(),sel_date.get_year(),sel_date.get_month());
	cout<<cmd<<endl;
	system(cmd);
}
//======================================================
void get_item(guchar i)
{
	item=result[i][1];	//取得$2字段
	def_v=result[i][2];	//取得$3字段
}
//======================================================
void fill_result()
{
	ifstream fin(ItemFile);
	string line;
	stringstream ss;
	can_sel_num=0;
	result_str="";
	while(getline(fin,line)){
		if(line.find(input)==string::npos)continue;
		//拆分line到result[][3]，并填充result_str。
		ss.clear();
		ss<<line;
		result[can_sel_num][2]="";
		getline(ss,result[can_sel_num][0],',');
		getline(ss,result[can_sel_num][1],',');
		getline(ss,result[can_sel_num][2]);
		ss.clear();
		ss<<can_sel_num+1<<"."<<result[can_sel_num][1]<<"_";
		ss>>line;
		result_str+=line;
		can_sel_num++;
		if(can_sel_num>=MaxSelect) break;
	}
	fin.close();
	if(can_sel_num==0){input.resize(input.length()-1,'\0');return;}
	if(can_sel_num==1){get_item(0);}
	display();
}
//======================================================
gboolean on_window1_key_press_event(GdkEvent *ev)
{
	if (ev->type != GDK_KEY_PRESS)
		return false;
	GdkEventKey* event = (GdkEventKey*)ev; 
	guint in=event->keyval;
	ustring ukey=event->string;
	ukey=ukey.lowercase();
	//gchar key=ukey.value_type;	//typedef gunichar 	value_type
	gchar key=ukey.data()[0];	//const char* 	data () const
	if(in==GDK_Escape) {cancel();return true;}
	if(in==GDK_F1) {on_B_today_clicked();return true;}
//        if(in==GDK_F2) {last_day();return true;}
//        if(in==GDK_F3) {next_day();return true;}
	if(in==GDK_BackSpace) key='B';
	//需要屏蔽2个按钮回车＋空格。
	if(in==' ') return true;
	if(in==GDK_Return) key='R';
//        if(in==GDK_Return) {key='R'; return true;}
	//if(in==GDK_space) key='S';
	if(input==""){
		if(key>='a'&&key<='z'){input=key;fill_result();}
		return true;
	}
	if(item==""){
		if(key>='a'&&key<='z'){input+=key;fill_result();return true;}
		if(key>='1'&&key<=('0'+can_sel_num)){input+=key;get_item(key-'0'-1);display();return true;}
		if(key=='B'){input.resize(input.length()-1,'\0');display();}
		return true;
	}
	if(value==""){
		if(key=='B'){input.resize(input.length()-1,'\0');item="";fill_result();return true;}
		if(key=='R'){if(def_v!=""){value=def_v;save();}return true;}
		if(key>='0'&&key<='9'){value+=key;display();}
		return true;
	}
	if(key=='B'){value.resize(value.length()-1,'\0');display();return true;}
	if(key=='R'){save();return true;}
	if(key>='0'&&key<='9'){value+=key;display();}
	if(key=='.'&&(value.find('.')==-1)){value+=key;display();}
	//if(key=='.'){value+=key;display();}
	return true;
	///usr/include/gtk-2.0/gdk/gdkkeysyms.h
	//return Gtk::EventBox::on_key_press_event(event);
}
//======================================================
int main(int argc, char* argv[])
{
	//-------------------------------------
	Gtk::Main ea(argc, argv);
//        sprintf(appdir,"%s",g_get_current_dir());
//
//        std::ofstream fout("/home/exp/tmp",ios::app);
//        fout<<Glib::get_prgname()<<endl;
//        fout<<Glib::get_home_dir ()<<endl;
//        fout<<Glib::get_current_dir ()<<endl;
//        fout.close();
//        std::string Glib::path_get_dirname 	(	const std::string & 	filename 	 )
	Glib::RefPtr<Gnome::Glade::Xml> xml = Gnome::Glade::Xml::create(GladeFile);
	xml->get_widget("window1", pW);
	xml->get_widget("label1", pL);
	xml->get_widget("image1", pI1);
	xml->get_widget("image2", pI2);
	xml->get_widget("image3", pI3);
	xml->get_widget("image4", pI4);
	xml->get_widget("image5", pI5);
	xml->get_widget("image6", pI6);
	xml->get_widget("image7", pI7);
	xml->get_widget("image8", pI8);
	xml->get_widget("statusbar1", pS);
	xml->get_widget("calendar", T_calendar);
//        xml->get_widget("togglebutton2", pT2);
	xml->get_widget("calendar1", pC);
	xml->get_widget("today", B_today);
	xml->get_widget("edit_in", B_edit_in);	//2编辑按钮
	xml->get_widget("edit_out", B_edit_out);
	xml->get_widget("chart_year", B_chart_year);	//2统计按钮
	xml->get_widget("chart_month", B_chart_month);

	T_calendar->signal_toggled().connect(sigc::ptr_fun(&on_T_calendar_toggled));
	pW->signal_event().connect(sigc::ptr_fun(&on_window1_key_press_event));
	pC->signal_day_selected().connect(sigc::ptr_fun(&on_calendar1_day_selected));
	B_today->signal_clicked().connect(sigc::ptr_fun(&on_B_today_clicked));
	B_edit_in->signal_clicked().connect(sigc::ptr_fun(&on_edit_in_clicked));
	B_edit_out->signal_clicked().connect(sigc::ptr_fun(&on_edit_out_clicked));
	B_chart_year->signal_clicked().connect(sigc::ptr_fun(&on_chart_year_clicked));
	B_chart_month->signal_clicked().connect(sigc::ptr_fun(&on_chart_month_clicked));
//        pW->signal_key_press_event().connect(sigc::ptr_fun(&mask_key));

	//pix = Gdk::Pixbuf::create_from_file(IconFile);
	pix = Gdk::Pixbuf::create_from_inline (-1, icon, false);
	pI2->set(Gdk::Pixbuf::create_from_inline (-1, cal, false));
	pI3->set(Gdk::Pixbuf::create_from_inline (-1, pedit, false));
	pI4->set(Gdk::Pixbuf::create_from_inline (-1, pedit, false));
	pI5->set(Gdk::Pixbuf::create_from_inline (-1, chart, false));
	pI6->set(Gdk::Pixbuf::create_from_inline (-1, chart, false));
	pI7->set(Gdk::Pixbuf::create_from_inline (-1, pig, false));
	pI8->set(Gdk::Pixbuf::create_from_inline (-1, pclock, false));
	pW->property_icon()=Gdk::Pixbuf::create_from_inline (-1, fe, false);
	//today.set_parse("2008年 01月 01日");//"2008-1-1");
	today.set_time_current();
	on_B_today_clicked();
	display();
	//gdk-pixbuf-csource --build-list cal calx24.png icon icon.png >pic.h
	//~/媒体/png/iToolbar_png 
	//☎  montage -background none -tile x1 -geometry 896x128 misc-blue.png button-blue.png misc-green.png button-green.png button-yellow.png button-red.png misc-red.png ee.png
	//convert ee.png -scale 168 icon.png
	//-------------------------------------
	//Gtk::Main::run(*pW);
	
//    pB->unset_flags(Gtk::CAN_FOCUS);
//    T_calendar->unset_flags(Gtk::CAN_FOCUS);
	ea.run(*pW);
}
//======================================================
